package com.egreen.pointsmall.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.egreen.common.States;
import com.egreen.common.pojo.DTO.pointsmall.UserLoginDTO;
import com.egreen.common.pojo.DTO.pointsmall.UserRegisterDTO;
import com.egreen.common.pojo.VO.pointsmall.OrdersDetailVO;
import com.egreen.common.pojo.VO.pointsmall.OrdersVO;
import com.egreen.common.pojo.entity.pointsmall.*;
import com.egreen.pointsmall.exception.PointsmallException;
import com.egreen.pointsmall.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author yyf
 * @since 2023-04-04
 */
@Controller
@RequestMapping("/user")
@Slf4j
public class PointsUserController {
    @Autowired
    private IPointsUserService pointuserService;
    @Autowired
    private IOrdersService ordersService;
    @Autowired
    private IOrdersDetailService ordersDetailService;
    @Autowired
    private IProductService productService;
    @Autowired
    private ICartService cartService;
    @Autowired
    private IUserAddressService userAddressService;

    @PostMapping("/register")
    String register(@Valid UserRegisterDTO userRegisterDTO
            , BindingResult bindingResult) {
        /**、
         * 用户注册
         * 校验的错误信息都会封装在bindingResult中
         * 前端校验注册字段是否为空，后端再次进行数据校验(使用springmvc的非空校验)
         */
        //如果有错误，直接输出既可以
        if (bindingResult.hasErrors()) {
            log.info("用户注册信息不能为空");
            throw new PointsmallException(States.USER_REGISTER_ERROR);
        }
        PointsUser pointsUser = pointuserService.register(userRegisterDTO);
        if (pointsUser == null) {
            log.info("用户注册");
            throw new PointsmallException(States.USER_REGISTER_ERROR);
        }
        //重定向转发页面
        return "redirect:/login";
        //return new Result(null,States.OK.getStates(),States.OK.getDescription());
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public String login(@Valid UserLoginDTO userLoginDTO, BindingResult bindingResult,
                        HttpSession session) {
        //进行非空校验
        if (bindingResult.hasErrors()) {
            log.info("用户登录信息不能为空");
            throw new PointsmallException(States.USER_INFO_NULL);
        }
        PointsUser pointuser = pointuserService.login(userLoginDTO);
        session.setAttribute("user", pointuser);
        //重定向到productCategory中进行加载首页数据
        return "redirect:/productCategory/main";
    }

    /**
     * 用户获取自己相关的订单
     *
     * @return
     */
    @GetMapping("/orderList")
    public ModelAndView ordersList(HttpSession session) {
        PointsUser user = (PointsUser) session.getAttribute("user");
        if (user == null) {
            throw new PointsmallException(States.NOT_LOGIN);
        }
        List<OrdersVO> list = new ArrayList<>();
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", user.getId());
        List<Orders> orders = ordersService.list(queryWrapper);
        for (Orders order : orders) {
            OrdersVO ordersVO = new OrdersVO();
            BeanUtils.copyProperties(order, ordersVO);
            QueryWrapper<OrdersDetail> detailQueryWrapper = new QueryWrapper<>();
            detailQueryWrapper.eq("order_id", order.getId());
            List<OrdersDetail> ordersDetailList = ordersDetailService.list(detailQueryWrapper);
            List<OrdersDetailVO> detailVOList = new ArrayList<>();
            for (OrdersDetail ordersDetail : ordersDetailList) {
                Product byId = productService.getById(ordersDetail.getProductId());
                OrdersDetailVO ordersDetailVO = new OrdersDetailVO();
                BeanUtils.copyProperties(byId, ordersDetailVO);
                BeanUtils.copyProperties(ordersDetail, ordersDetailVO);
                detailVOList.add(ordersDetailVO);
            }
            ordersVO.setOrdersDetailList(detailVOList);
            list.add(ordersVO);
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("orderList");
        modelAndView.addObject("orderList", list);
        modelAndView.addObject("cartList", cartService.getCartVoList(user.getId()));
        return modelAndView;
    }

    /**
     * 返回当前用户地址的列表
     *
     * @return
     */
    @GetMapping("/addressList")
    public ModelAndView addressList(HttpSession session) {
        PointsUser user = (PointsUser) session.getAttribute("user");
        if (user == null) {
            throw new PointsmallException(States.NOT_LOGIN);
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("userAddressList");
        QueryWrapper<UserAddress> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", user.getId());
        modelAndView.addObject("addressList", userAddressService.list(queryWrapper));
        modelAndView.addObject("cartList", cartService.getCartVoList(user.getId()));
        return modelAndView;
    }

    /**
     * 退出登录
     * @param session
     * @return
     */
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        return "redirect:/productCategory/main";
    }
    @GetMapping("/delete/{id}")
    public ModelAndView delete(HttpSession session, @PathVariable("id")Integer id){
        PointsUser user = (PointsUser) session.getAttribute("user");
        if (user==null){
            throw new PointsmallException(States.NOT_LOGIN);
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("userAddressList");
        userAddressService.removeById(id);
        QueryWrapper<UserAddress> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", user.getId());
        modelAndView.addObject("addressList",userAddressService.list(queryWrapper));
        modelAndView.addObject("cartList", cartService.getCartVoList(user.getId()));
        return modelAndView;

    }


}

